;Adam Wilford
;Lab 2

    LIST    p=16F887        ;set processor
    INCLUDE "P16F887.inc"

    ;set config values
    __CONFIG    _CONFIG1,  _IESO_OFF & _FCMEN_OFF & _PWRTE_ON  & _WDT_OFF & _INTOSCIO & _BOR_ON & _LVP_OFF & _CP_OFF &_CPD_OFF & _MCLRE_OFF &_INTRC_OSC_NOCLKOUT
	__CONFIG    _CONFIG2,	_WRT_OFF & _BOR40V

    ORG 0


    CBLOCK 0x20
        RE                  ;used to store value of w for subtraction
        ISMIDDLE            ;flag used to check if pot is exactly in the middle
    ENDC

Start:
                            ;configure as analog input
    BANKSEL     TRISA
    BSF         TRISA,0
    CLRF        TRISD
                            ;seelect analog channel 1
    BANKSEL     ANSEL
    BSF         ANSEL,0
                            ;set analog options, including left justified
    BANKSEL     ADCON1
    CLRF        ADCON1

Loop:
                            ;wait for signal stabilization
    NOP
    NOP
    NOP
    NOP
    NOP
    BANKSEL     ADCON0
    MOVLW       0x41        ;configure analog conversion
    MOVWF       ADCON0
    BSF         ADCON0,0    ;turn ADC on

    BSF         ADCON0,1    ;begin ADC
    BTFSS       ADCON0,1    ;loop until ADC is complete
    GOTO        $-1
    CLRF        RE          ;clear for safety
    CLRF        PORTD
    CLRF        ISMIDDLE
    MOVFW       ADRESH      ;move the ADRESH into temp variable prior to operations
    MOVWF       RE


                            ;check to see if the pot is exactly centered
                            ;if it is, restart the loop
    SUBLW       0X80
    BTFSC       STATUS,2
    BSF         ISMIDDLE,0
    BTFSC       ISMIDDLE,0
    CLRF        PORTD
    BTFSC       ISMIDDLE,0
    GOTO        Loop
                            ;check ranges using subtraction and zero bit from
                            ;status register
    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0xE0
    BTFSC       STATUS,2
    BSF         PORTD,7

    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0XC0
    BTFSC       STATUS,2
    BSF         PORTD,6

    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0Xa0
    BTFSC       STATUS,2
    BSF         PORTD,5

    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0X80
    BTFSC       STATUS,2
    BSF         PORTD,4

    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0X60
    BTFSC       STATUS,2
    BSF         PORTD,3

    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0X40
    BTFSC       STATUS,2
    BSF         PORTD,2

    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0X20
    BTFSC       STATUS,2
    BSF         PORTD,1

    MOVFW       RE
    ANDLW       B'11100000'
    SUBLW       0X0
    BTFSC       STATUS,2
    BSF         PORTD,0

    GOTO        Loop            ;restart the loop

    END